// Minimal background script for Element Controller
class BackgroundScript {
  constructor() {
    this.init();
  }

  init() {
    this.setupInstallHandler();
    console.log('Element Controller: Background script initialized');
  }

  setupInstallHandler() {
    chrome.runtime.onInstalled.addListener(async (details) => {
      try {
        console.log('Element Controller: Extension installed/updated', details);
        
        if (details.reason === 'install') {
          // Initialize storage with default settings
          const defaultRules = { urlRules: [] };
          await chrome.storage.sync.set({
            'elementControllerRules': defaultRules,
            'elementControllerVersion': '1.0.0'
          });
          console.log('Element Controller: First install setup completed');
          
          // Show welcome notification with fallback mechanism
          this.showWelcomeMessage();
        }
      } catch (error) {
        console.error('Element Controller: Error during install/update:', error);
      }
    });
  }

  showWelcomeMessage() {
    try {
      chrome.notifications.create('welcome', {
        type: 'basic',
        iconUrl: chrome.runtime.getURL('icons/icon128.png'),
        title: 'Element Controller 已安装',
        message: '点击扩展图标开始控制网页元素的显示和隐藏！',
        priority: 2
      }, (notificationId) => {
        if (chrome.runtime.lastError) {
          console.error('通知创建失败:', chrome.runtime.lastError);
          this.saveWelcomeFlag();
        }
      });
    } catch (err) {
      console.error('显示欢迎消息失败:', err);
      this.saveWelcomeFlag();
    }
  }

  async saveWelcomeFlag() {
    try {
      await chrome.storage.local.set({ 'welcomeShown': true });
      console.log('Element Controller: Welcome flag saved as fallback');
    } catch (error) {
      console.error('Element Controller: Failed to save welcome flag:', error);
    }
  }
}

// Initialize background script
const backgroundScript = new BackgroundScript();